﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Text;
using CommonHelp;
using Core.Unity;
using DbHelp;
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Services {
    /// <summary>
    /// PM2.5
    /// </summary>
    public class Pm25InfoService : Core.Unity.IInfoService {
        private EventHandler<ReceivedDataEventArgs> _ReceivedDataEvents;
        private List<PM25Info> _DataList;

        public event EventHandler<ReceivedDataEventArgs> AfterQueryData {
            add {
                _ReceivedDataEvents += value;
            }
            remove {
                _ReceivedDataEvents -= value;
            }
        }

        public void OnModelCreating(ref DbModelBuilder modelBuilder) {
            string tableName = "WEBDATA_PM25" + DateTime.Now.Year.ToString();
            modelBuilder.Entity<PM25Info>().ToTable(tableName);
        }

        public void QueryData() {
            string url = ConfigurationManager.AppSettings["QueryPM25Url"].ToString();
            HttpHelper http = new HttpHelper(url);
            http.GetAsync(AfterGetData);
        }

        private void AfterGetData(string responseString) {
            try {
                List<PM25Info> infos = JsonConvert.DeserializeObject<List<PM25Info>>(responseString);
                foreach (var item in infos) {
                    item.ID = Guid.NewGuid().ToString();
                }
                _DataList = infos;

                if (_ReceivedDataEvents != null) {
                    _ReceivedDataEvents(this, new ReceivedDataEventArgs(infos));
                }
            }
            catch (Exception ex) {
                CommonHelp.LogHelper.Error(ex);
                if (_ReceivedDataEvents != null) {
                    _ReceivedDataEvents(this, new ReceivedDataEventArgs(ex));
                }
            }
        }

        public void SaveData(object data) {
            using (WebDataContext db = new WebDataContext()) {
                List<PM25Info> list = data as List<PM25Info>;
                DbSet<PM25Info> infos = db.Set<PM25Info>();
                foreach (var item in list) {
                    if (infos.Any(a => a.Station_code == item.Station_code && a.Time_point == item.Time_point)) {
                        continue;
                    }

                    infos.Add(item);
                }
                db.SaveChanges();
            }
        }
    }
}
